package com.lksoft.bz.command;

import java.util.HashMap;
import java.util.Map.Entry;

import com.lksoft.bz.Bead;
import com.lksoft.bz.BeadDB;
import com.lksoft.bz.Bz;
import com.lksoft.bz.StitchPattern;

/**
 * Command that draws some beads of a specified color on the stitch pattern
 * 
 * @author lake
 *
 */
public class DrawBeadsCommand implements Command {
	// The program
	Bz bz;
	
	// Hash of coordinates -> original color
	HashMap<Integer, Integer> originalColors = new HashMap<>();
	
	// Bead that was drawed
	Bead bead;
	
	/**
	 * @param bz The program
	 */
	public DrawBeadsCommand(Bz bz, Bead paletteBead){
		this.bz = bz;
		this.bead = paletteBead;
	}
	
	/**
	 * Adds a draw event (a change in the pattern)
	 * @param x Draw coordinates
	 * @param y Draw coortinates
	 * @param originalColor Original color that was overwritten
	 */
	public void addChange(int x, int y, int originalColor){
		originalColors.put(x+y*StitchPattern.MAX_SIZE, originalColor);
	}

	@Override
	public void redo() {
		boolean usedBeadsChanged = false;
		for( int k : originalColors.keySet() ){
			int x = k % StitchPattern.MAX_SIZE;
			int y = k / StitchPattern.MAX_SIZE;
			
			usedBeadsChanged |= bz.getStitchPanel().getStitchPattern().setBead(x, y, bead);
		}
		
		if( usedBeadsChanged ){
			bz.fireUsedBeadsChange();
		}
		bz.redraw();
	}

	@Override
	public void undo() {
		boolean usedBeadsChanged = false;
		for( Entry<Integer, Integer> e : originalColors.entrySet() ){
			int x = e.getKey() % StitchPattern.MAX_SIZE;
			int y = e.getKey() / StitchPattern.MAX_SIZE;
			int color = e.getValue();
			
			if( color == 0 ){
				usedBeadsChanged |= bz.getStitchPanel().getStitchPattern().removeBead(x, y);
			} else {
				usedBeadsChanged |= bz.getStitchPanel().getStitchPattern().setBead(x, y, BeadDB.get().getBeadMap().get(color));
			}
		}
		
		if( usedBeadsChanged ){
			bz.fireUsedBeadsChange();
		}
		bz.redraw();
	}

	/**
	 * @return Whether there was any change reported at all
	 */
	public boolean hasAnyChange() {
		return !originalColors.isEmpty();
	}

}
